// src/screens/HomeScreen.js
import React, { useState, useEffect, useCallback } from 'react';
import { 
  View, 
  Text, 
  TouchableOpacity, 
  Image, 
  Alert, 
  StyleSheet, 
  ActivityIndicator,
  RefreshControl
} from 'react-native';
import api from '../services/api';
import { useSelector } from 'react-redux';
import CustomHeader from '../components/CustomHeader';

const HomeScreen = ({ navigation }) => {
  const [users, setUsers] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const userInfo = useSelector(state => state.user.userInfo);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      // 获取筛选条件
      const filterResponse = await api.getFilters();
      let filters = {};
      if (filterResponse.success) {
        filters = filterResponse.data;
      }
      
      // 根据筛选条件获取匹配用户
      const response = await api.getFilteredUsers(filters);
      console.log('获取到的用户数据:', response);
      
      // 确保正确处理响应数据
      if (response.success) {
        setUsers(response.data || []);
        setCurrentIndex(0); // 重置索引
      } else {
        setUsers([]);
        Alert.alert('提示', response.message || '获取用户失败');
      }
    } catch (error) {
      console.error('获取用户失败:', error);
      setUsers([]);
      Alert.alert('错误', '获取用户失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  }, []);

  // 下拉刷新
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      // 获取筛选条件
      const filterResponse = await api.getFilters();
      let filters = {};
      if (filterResponse.success) {
        filters = filterResponse.data;
      }
      
      const response = await api.getFilteredUsers(filters);
      if (response.success) {
        setUsers(response.data || []);
        setCurrentIndex(0);
      } else {
        Alert.alert('提示', response.message || '获取用户失败');
      }
    } catch (error) {
      Alert.alert('错误', '刷新失败: ' + (error.message || '未知错误'));
    } finally {
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  const handleSwipe = async (action) => {
    if (sending) return;
    
    const targetUser = users[currentIndex];
    if (!targetUser) return;
    
    setSending(true);
    
    try {
      // 处理滑动操作，发送 like / dislike 请求
      const response = await api.sendSwipeAction(targetUser.id, action);
      
      // 检查是否匹配成功
      if (action === 'like' && response.data?.matched) {
        Alert.alert(
          '匹配成功', 
          `与 ${targetUser.name} 匹配成功！`,
          [
            { text: '继续' },
            {
              text: '查看资料',
              onPress: () => navigation.navigate('MatchProfile', { user: targetUser })
            }
          ]
        );
      }
      
      // 移动到下一个用户
      setCurrentIndex(currentIndex + 1);
    } catch (error) {
      console.error('操作失败:', error);
      Alert.alert('错误', '操作失败: ' + (error.message || '未知错误'));
    } finally {
      setSending(false);
    }
  };

  // 跳转到筛选页面
  const goToFilter = () => {
    navigation.navigate('Filter');
  };

  // 查看用户详细资料
  const viewUserProfile = (user) => {
    navigation.navigate('MatchProfile', { 
      userId: user.id, 
      userName: user.name,
      user: user
    });
  };

  // 如果没有更多用户了
  if (currentIndex >= users.length && users.length > 0) {
    return (
      <View style={styles.container}>
        <CustomHeader title="发现" onFilterPress={goToFilter} />
        <View style={styles.emptyContainer}>
          <Text style={styles.title}>没有更多用户了</Text>
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.actionButton} onPress={fetchUsers}>
              <Text style={styles.buttonText}>刷新</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.actionButton, styles.filterButton]} onPress={goToFilter}>
              <Text style={styles.buttonText}>筛选</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

  // 显示加载指示器
  if (loading) {
    return (
      <View style={styles.container}>
        <CustomHeader title="发现" onFilterPress={goToFilter} />
        <View style={styles.centerContainer}>
          <ActivityIndicator size="large" color="#0000ff" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </View>
    );
  }

  // 如果还没有用户数据
  if (users.length === 0) {
    return (
      <View style={styles.container}>
        <CustomHeader title="发现" onFilterPress={goToFilter} />
        <View style={styles.emptyContainer}>
          <Text style={styles.title}>暂无推荐用户</Text>
          <View style={styles.buttonRow}>
            <TouchableOpacity style={styles.actionButton} onPress={fetchUsers}>
              <Text style={styles.buttonText}>刷新</Text>
            </TouchableOpacity>
            <TouchableOpacity style={[styles.actionButton, styles.filterButton]} onPress={goToFilter}>
              <Text style={styles.buttonText}>筛选</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

  const currentUser = users[currentIndex];

  return (
    <View style={styles.container}>
      <CustomHeader title="发现" onFilterPress={goToFilter} />
      
      <View style={styles.contentContainer}>
        <View style={styles.card}>
          {currentUser.avatar ? (
            <TouchableOpacity onPress={() => viewUserProfile(currentUser)}>
              <Image 
                source={{ uri: currentUser.avatar }} 
                style={styles.avatar}
                resizeMode="cover"
              />
            </TouchableOpacity>
          ) : (
            <TouchableOpacity onPress={() => viewUserProfile(currentUser)} style={styles.placeholderAvatar}>
              <Text style={styles.avatarText}>{currentUser.name?.charAt(0) || 'U'}</Text>
            </TouchableOpacity>
          )}
          
          <Text style={styles.name}>{currentUser.name}</Text>
          
          {currentUser.location && (
            <Text style={styles.location}>{currentUser.location}</Text>
          )}
          
          <View style={styles.buttonContainer}>
            <TouchableOpacity 
              style={[styles.swipeButton, styles.dislikeButton]} 
              onPress={() => handleSwipe('dislike')}
              disabled={sending}
            >
              <Text style={styles.buttonText}>👎</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={[styles.swipeButton, styles.likeButton]} 
              onPress={() => handleSwipe('like')}
              disabled={sending}
            >
              <Text style={styles.buttonText}>👍</Text>
            </TouchableOpacity>
          </View>
          
          {sending && (
            <View style={styles.sendingOverlay}>
              <ActivityIndicator size="small" color="#fff" />
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  contentContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  centerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  card: {
    width: '100%',
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 20,
    alignItems: 'center',
    elevation: 3,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
    position: 'relative'
  },
  avatar: {
    width: 150,
    height: 150,
    borderRadius: 75,
    marginBottom: 20
  },
  placeholderAvatar: {
    width: 150,
    height: 150,
    borderRadius: 75,
    backgroundColor: '#ddd',
    marginBottom: 20,
    justifyContent: 'center',
    alignItems: 'center'
  },
  avatarText: {
    fontSize: 60,
    fontWeight: 'bold',
    color: '#888'
  },
  name: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10
  },
  location: {
    fontSize: 16,
    color: '#666',
    marginBottom: 20
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%'
  },
  swipeButton: {
    width: 70,
    height: 70,
    borderRadius: 35,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 2
  },
  likeButton: {
    backgroundColor: '#4CAF50'
  },
  dislikeButton: {
    backgroundColor: '#F44336'
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
    fontSize: 24
  },
  actionButton: {
    backgroundColor: '#2196F3',
    paddingVertical: 15,
    paddingHorizontal: 30,
    borderRadius: 30,
    marginHorizontal: 10,
  },
  filterButton: {
    backgroundColor: '#FF9800',
  },
  buttonRow: {
    flexDirection: 'row',
    marginTop: 20,
  },
  title: {
    fontSize: 20,
    textAlign: 'center',
    marginBottom: 20
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16
  },
  sendingOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10
  }
});

export default HomeScreen;